// ============================================================================
// File: pkg/config/config.go
// ============================================================================
package config

import (
	"fmt"
	"os"
	"time"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Version  string           `yaml:"version"`
	Root     string           `yaml:"root"`
	Registry RegistryConfig   `yaml:"registry"`
	Storage  StorageConfig    `yaml:"storage"`
	Lazy     LazyLoadConfig   `yaml:"lazy_loading"`
	Logging  LoggingConfig    `yaml:"logging"`
	Recovery RecoveryConfig   `yaml:"recovery"`
}

type RegistryConfig struct {
	URL        string        `yaml:"url"`
	Auth       AuthConfig    `yaml:"auth"`
	Timeout    time.Duration `yaml:"timeout"`
	MaxRetries int           `yaml:"max_retries"`
}

type AuthConfig struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
	Token    string `yaml:"token"`
}

type StorageConfig struct {
	Backend       string `yaml:"backend"`
	CacheSize     string `yaml:"cache_size"`
	GCThreshold   float64 `yaml:"gc_threshold"`
	BlockSize     int64  `yaml:"block_size"`      // v2.0: Block size for dedup
	MaxConcurrent int    `yaml:"max_concurrent"`  // v2.0: Max concurrent downloads
}

type LazyLoadConfig struct {
	Enabled   bool          `yaml:"enabled"`
	Prefetch  PrefetchConfig `yaml:"prefetch"`
}

type PrefetchConfig struct {
	Enabled       bool     `yaml:"enabled"`
	Paths         []string `yaml:"paths"`
	MaxSize       string   `yaml:"max_size"`
	ConcurrentJobs int     `yaml:"concurrent_jobs"`
}

type LoggingConfig struct {
	Level  string `yaml:"level"`
	File   string `yaml:"file"`
	Format string `yaml:"format"`
}

type RecoveryConfig struct {
	Enabled       bool          `yaml:"enabled"`
	CheckInterval time.Duration `yaml:"check_interval"`
}

func Load(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	cfg := &Config{}
	if err := yaml.Unmarshal(data, cfg); err != nil {
		return nil, err
	}

	// Set defaults
	if cfg.Root == "" {
		cfg.Root = "/var/lib/onyx"
	}
	if cfg.Registry.URL == "" {
		cfg.Registry.URL = "https://registry-1.docker.io"
	}
	if cfg.Registry.Timeout == 0 {
		cfg.Registry.Timeout = 30 * time.Second
	}
	if cfg.Registry.MaxRetries == 0 {
		cfg.Registry.MaxRetries = 3
	}
	if cfg.Storage.Backend == "" {
		cfg.Storage.Backend = "ext4"
	}
	if cfg.Storage.BlockSize == 0 {
		cfg.Storage.BlockSize = 4 * 1024 * 1024 // 4MB
	}
	if cfg.Storage.MaxConcurrent == 0 {
		cfg.Storage.MaxConcurrent = 10
	}
	if cfg.Lazy.Prefetch.ConcurrentJobs == 0 {
		cfg.Lazy.Prefetch.ConcurrentJobs = 5
	}
	if cfg.Recovery.CheckInterval == 0 {
		cfg.Recovery.CheckInterval = 5 * time.Minute
	}

	return cfg, cfg.Validate()
}

func (c *Config) Validate() error {
	if c.Storage.BlockSize < 1024*1024 {
		return fmt.Errorf("block_size must be at least 1MB")
	}
	if c.Storage.MaxConcurrent < 1 {
		return fmt.Errorf("max_concurrent must be at least 1")
	}
	return nil
}
